#include "chartplotter.h"

void ChartPlotter::drawCharts(const QVector<QVector<int>> &data) {
    setData(data);
    QThreadPool::globalInstance()->start(new ChartTask(this, data));
}

void ChartPlotter::paint(QPainter *painter) {
    if (!m_data.isEmpty()) {
        drawRingChart(painter);
    }
}

void ChartPlotter::drawRingChart(QPainter *painter) {
    int goodCount = 0;
    int defectCount = 0;
    QMap<int, int> defectTypeCount;

    for (const auto& list : m_data) {
        if (list.isEmpty()) {
            ++goodCount;
        } else {
            ++defectCount;
            for (const int& defect : list) {
                defectTypeCount[defect]++;
            }
        }
    }

    int totalCount = goodCount + defectCount;

    QPieSeries *series = new QPieSeries();
    series->append("Good", goodCount);
    series->append("Defect", defectCount);

    QPieSlice *goodSlice = series->slices().at(0);
    QPieSlice *defectSlice = series->slices().at(1);

    goodSlice->setLabel(QString("Good: %1 (%2%)").arg(goodCount).arg((double)goodCount / totalCount * 100, 0, 'f', 2));
    defectSlice->setLabel(QString("Defect: %1 (%2%)").arg(defectCount).arg((double)defectCount / totalCount * 100, 0, 'f', 2));
    defectSlice->setExploded();
    defectSlice->setLabelVisible();

    QChart *chart = new QChart();
    chart->addSeries(series);
    chart->setTitle("Good vs Defect");

    QChartView chartView(chart);
    chartView.setRenderHint(QPainter::Antialiasing);

    chartView.render(painter);
}
